package org.example.chat.aop;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.chat.aop.annotation.SaveLog;
import org.example.chat.api.CommonResult;
import org.example.chat.api.ResultCode;
import org.example.chat.dao.SystemLogRepository;
import org.example.chat.entity.SystemLog;
import org.example.chat.security.entity.LoginUser;
import org.example.chat.utils.BaseUtils;
import org.example.chat.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
public class SaveLogAspect {

    @Autowired
    private BaseUtils baseUtils;
    @Autowired
    private SystemLogRepository systemLogRepository;

    @Pointcut("@annotation(org.example.chat.aop.annotation.SaveLog)")
    public void logPointcut() {
    }

    @AfterReturning(value = "logPointcut()", returning = "result")
    public void saveLog(JoinPoint joinPoint, Object result) {
        CommonResult<Object> commonResult = (CommonResult<Object>) result;
        // 方法执行成功后记录日志
        if (commonResult.getCode() == ResultCode.SUCCESS.getCode()) {
            // 获取切入点方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            // 获取切入点方法上的注解
            SaveLog annotation = method.getAnnotation(SaveLog.class);
            // 获取注解参数
            String content = annotation.content();
            int logType = annotation.logType();
            boolean isRecordParam = annotation.isRecordParam();
            // 创建日志对象
            SystemLog systemLog = new SystemLog();
            systemLog.setLogType(logType);
            LoginUser loginUserInfo = CommonUtils.getLoginUserInfo();
            systemLog.setAccount(loginUserInfo.getUsername());
            systemLog.setContent(content);
            systemLog.setOptionTime(LocalDateTime.now());
            systemLog.setIp(baseUtils.getClientIp());
            if (isRecordParam) {
                systemLog.setParam(JSONUtil.toJsonStr(joinPoint.getArgs()));
            }
            // 保存
            systemLogRepository.save(systemLog);
        }
    }
}
